package cn.tedu.ykmall.user.webapi.security;

import cn.tedu.ykmall.pojo.userClient.dto.UserLoginDTO;
import cn.tedu.ykmall.user.webapi.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        System.out.println("根据用户昵称查询尝试登录的用户信息，昵称=" + s);
        UserLoginDTO user = userMapper.getUserByNickname(s);
        System.out.println("通过持久层进行查询，结果=" + user);

        if (user == null) {
            System.out.println("根据昵称没有查询到有效的用户数据，将抛出异常");
            throw new BadCredentialsException("登录失败，昵称不存在！");
        }

        System.out.println("查询到匹配的用户数据，需要将此数据转换为UserDetails并返回");
        UserDetails userDetails = User.builder()
                .username(user.getNickname())
                .password(user.getPassword())
                .authorities(Collections.emptyList())
                .accountExpired(false)
                .accountLocked(false)
                .credentialsExpired(false)
                .disabled(false)
                .build();
        System.out.println("转换得到UserDetails=" + userDetails);
        return userDetails;
    }
}
